package org.canaan.mybatis;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * @author Canaan
 * @date 2017/10/15
 */
class ReflectHelper {
    private final static Logger logger = LoggerFactory.getLogger(ReflectHelper.class);

    static Object getFieldValue(Object obj, String fieldName) throws IllegalAccessException {

        if (obj == null) {
            return null;
        }

        Field targetField = getTargetField(obj.getClass(), fieldName);
        return FieldUtils.readField(targetField, obj, true);
    }

    private static Field getTargetField(Class<?> targetClass, String fieldName) {
        Field field;

        field = FieldUtils.getDeclaredField(targetClass, fieldName, true);
        if (field == null) {
            field = getTargetField(targetClass.getSuperclass(), fieldName);
        }

        return field;
    }

     static void setFieldValue(Object obj, String fieldName, Object value) {
        if (null == obj) {
            return;
        }
        Field targetField = getTargetField(obj.getClass(), fieldName);
        try {
            FieldUtils.writeField(targetField, obj, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
